package com.corn.flink.lesson1;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.PathUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.operators.translation.TupleWrappingCollector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2022/7/19 16:41
 */

public class FlinkBatchHelloWorld {
    // 批处理
    public static void main(String[] args) throws Exception {
        // 1. 准备环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        String filePath = FileUtil.getAbsolutePath("classpath:input/wordcount.txt");
        // 2. 从文件中读取数据 按行读取
        DataSource<String> ds = env.readTextFile(filePath, "utf-8");
        // 3. 数据格式转换改为元组 (word,1) (flink,1)类似
        FlatMapOperator<String, Tuple2<String, Long>> flatMapOperator = ds.flatMap((String line, Collector<Tuple2<String, Long>> out) -> {
            String[] words = line.split(" ");
            for (String word : words) {
                out.collect(Tuple2.of(word, 1L));
            }
        }).returns(Types.TUPLE(Types.STRING, Types.LONG));
        // 4. 按word进行分组
        UnsortedGrouping<Tuple2<String, Long>> grouped = flatMapOperator.groupBy(0);
        // 5. 分组聚合统计
        AggregateOperator<Tuple2<String, Long>> result = grouped.sum(1);
        result.print();

        ds.flatMap((String line, Collector<Tuple2<String, Integer>> out)->{
            String[] words = line.split(" ");
            for (String word : words) {
                Tuple2<String, Integer> tuple2 = Tuple2.of(word, 1);
                out.collect(tuple2);
            }
        }).returns(Types.TUPLE(Types.STRING, Types.INT)).groupBy(0).sum(1).print();

    }
}
